package com.hanzhong.travel.controller;

import com.hanzhong.travel.entity.User;
import com.hanzhong.travel.entity.dto.LoginDTO;
import com.hanzhong.travel.entity.dto.LoginResponseDTO;
import com.hanzhong.travel.service.UserService;
import com.hanzhong.travel.util.JwtTokenUtil;
import com.hanzhong.travel.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.util.Collections;

@RestController
@RequestMapping("/api/auth")
public class AuthController {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private UserService userService;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    
    @Autowired
    private PasswordEncoder passwordEncoder;

    @PostMapping("/login")
    public Result<LoginResponseDTO> login(@RequestBody LoginDTO loginDTO) {
        try {
            System.out.println("收到登录请求: " + loginDTO.getUsername());
            
            // 直接从数据库查询用户，不使用Spring Security的认证流程
            User user = userService.findByUsername(loginDTO.getUsername());
            if (user == null) {
                System.out.println("用户不存在: " + loginDTO.getUsername());
                return Result.error("用户名或密码错误");
            }
            
            // 手动验证密码
            if (!passwordEncoder.matches(loginDTO.getPassword(), user.getPassword())) {
                System.out.println("密码不匹配，用户提供: " + loginDTO.getPassword());
                System.out.println("数据库密码: " + user.getPassword());
                return Result.error("用户名或密码错误");
            }
            
            System.out.println("密码验证成功");
            
            // 创建认证对象并设置上下文
            UserDetails userDetails = new org.springframework.security.core.userdetails.User(
                user.getUsername(),
                user.getPassword(),
                Collections.singletonList(new SimpleGrantedAuthority("ROLE_USER"))
            );
            
            Authentication authentication = new UsernamePasswordAuthenticationToken(
                userDetails, null, userDetails.getAuthorities()
            );
            SecurityContextHolder.getContext().setAuthentication(authentication);
            
            // 生成JWT令牌
            String token = jwtTokenUtil.generateToken(userDetails);
            
            LoginResponseDTO responseDTO = new LoginResponseDTO(
                    token,
                    user.getId(),
                    user.getUsername(),
                    user.getNickname()
            );
            
            System.out.println("登录成功，返回token: " + token.substring(0, 10) + "...");
            
            return Result.success(responseDTO);
        } catch (Exception e) {
            System.out.println("登录失败: " + e.getMessage());
            e.printStackTrace();
            return Result.error("用户名或密码错误");
        }
    }

    @PostMapping("/register")
    public Result<Object> register(@RequestBody User user) {
        // 检查用户名是否已存在
        if (userService.findByUsername(user.getUsername()) != null) {
            return Result.error("用户名已存在");
        }
        
        boolean success = userService.register(user);
        if (success) {
            return Result.success();
        } else {
            return Result.error("注册失败");
        }
    }
} 